package com.lee.xcore.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.viewbinding.ViewBinding
import com.lee.xcore.eventbus.Event

abstract class BaseVMFragment<VB : ViewBinding, VM : ViewModel> : Fragment(), IBasisView {
    private lateinit var _vb: VB
    private lateinit var _vm: VM
    protected val V get() = _vb
    protected val M get() = _vm

    lateinit var mContext: AppCompatActivity

    var contentView: View? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mContext = context as AppCompatActivity
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        if(contentView==null){
            if (isEventBusEnable()) {
                Event.getInstance().register(this)
            }
            beforeSetContentView()
            _vb = getViewBinding(inflater, container)
            _vm = getViewModel()
            contentView = _vb.root
            beforeInitView(savedInstanceState)
            initView(savedInstanceState)
            createEvent()
            createObserver()
        }

        return contentView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initStateBar()
    }

    private var isLoaded = false
    override fun onResume() {
        super.onResume()
        if (!isLoaded && !isHidden) {
            loadData()
            isLoaded = true
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        if (isEventBusEnable()) {
            Event.getInstance().unregister(this)
        }
    }



    override fun onDestroyView() {
        super.onDestroyView()
        contentView = null
        isLoaded = false
    }

    protected abstract fun getViewBinding(inflater: LayoutInflater, viewGroup: ViewGroup?): VB
    protected abstract fun getViewModel(): VM
}